package com.itcast.excel.test;

import com.itcast.excel.domain.User;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/generate")
@Controller
public class Generate {
    @PostMapping("")
    public void genarate(User user, HttpServletResponse response){
        ServletOutputStream outputStream1=null;
        InputStream inputStream=null;
        try {
            OutputStream outputStream=new FileOutputStream("C:\\Users\\李赛飞\\Desktop\\学生表.xlsx");
            ExcelWriter excelWriter=new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
            Sheet sheet=new Sheet(1,0,User.class);
            sheet.setSheetName("sheet1");
            List<User> list=new ArrayList<>();
            for (int i=0;i<100000;i++){
                list.add(user);
            }
            excelWriter.write(list,sheet);
            excelWriter.finish();
            //表的下载
            File file=new File("C:\\Users\\李赛飞\\Desktop\\学生表.xlsx");
            String fileName=file.getName();
            fileName=new String(fileName.getBytes("utf-8"),"iso8859-1");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition","attachment;fileName="+fileName);
            byte[] bytes=new byte[1024];
            outputStream1 = response.getOutputStream();
            inputStream=new BufferedInputStream(new FileInputStream(file));
            int len=0;
            while ((len=inputStream.read(bytes))!=-1){
                outputStream1.write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (outputStream1!=null){
                    outputStream1.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }
}
